package com.oasystem.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Timer;
import java.util.TimerTask;

import com.oasystem.utils.BackupConfigUtil;

public final class BackupDBService {
	private static Timer timer = new Timer();
	private static TimerTask task;
	private static boolean isRunning = false;
	public static String hour = "3";
	protected static String backuppath;
	protected static String username;
	protected static String password;
	protected static String database;
	protected static String mysqlBinPath;

	public static void update(long period) {
		backuppath = BackupConfigUtil.getParam("backuppath");
		username = BackupConfigUtil.getParam("username");
		password = BackupConfigUtil.getParam("password");
		database = BackupConfigUtil.getParam("database");
		mysqlBinPath = BackupConfigUtil.getParam("mysqlBinPath");
		if (task != null) {
			task.cancel();
		}
		task = new BackupTask();
		timer.schedule(task, 0, period);
		isRunning = true;
	}

	public static boolean isRunningBackup() {
		return isRunning;
	}

	public static void stopBackup() {
		task.cancel();
		isRunning = false;
	}

	public static void restore(String fileName) throws IOException {
		backuppath = BackupConfigUtil.getParam("backuppath");
		username = BackupConfigUtil.getParam("username");
		password = BackupConfigUtil.getParam("password");
		database = BackupConfigUtil.getParam("database");
		mysqlBinPath = BackupConfigUtil.getParam("mysqlBinPath");
		StringBuilder sb = new StringBuilder();
		sb.append(BackupDBService.mysqlBinPath);
		sb.append("mysql.exe -u");
		sb.append(BackupDBService.username);
		sb.append(" -p");
		sb.append(BackupDBService.password);
		sb.append(" ");
		sb.append(BackupDBService.database);

		try {
			String fPath = BackupConfigUtil.getParam("backuppath") + "/"
					+ fileName;
			Runtime rt = Runtime.getRuntime();
			// 调用 mysql 的 cmd:
			Process child = rt.exec(sb.toString());
			OutputStream out = child.getOutputStream();// 控制台的输入信息作为输出流
			String inStr;
			StringBuffer sbuf = new StringBuffer("");
			String outStr;
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(fPath), "utf8"));
			while ((inStr = br.readLine()) != null) {
				sbuf.append(inStr + "\r\n");
			}
			outStr = sbuf.toString();

			OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
			writer.write(outStr);
			// 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
			writer.flush();
			// 别忘记关闭输入输出流
			out.close();
			br.close();
			writer.close();

			System.out.println("");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class BackupTask extends TimerTask {

	@Override
	public void run() {
		System.out.println("正在備份。。。");
		File path = new File(BackupDBService.backuppath);
		if (!path.exists()) {
			path.mkdir();
		}
		// File batFilePath = new File(Object.class.getResource("/").toURI());
		StringBuilder sb = new StringBuilder();
		sb.append(BackupDBService.mysqlBinPath);
		sb.append("mysqldump -u");
		sb.append(BackupDBService.username);
		sb.append(" -p");
		sb.append(BackupDBService.password);
		sb.append(" ");
		sb.append(BackupDBService.database);

		try {
			Process child = Runtime.getRuntime().exec(sb.toString());
			InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
			InputStreamReader xx = new InputStreamReader(in, "utf8");// 设置输出流编码为utf8。这里必须是utf8，否则从流中读入的是乱码
			String inStr;
			StringBuffer sbuf = new StringBuffer("");
			String outStr;
			// 组合控制台输出信息字符串
			BufferedReader br = new BufferedReader(xx);
			while ((inStr = br.readLine()) != null) {
				sbuf.append(inStr + "\r\n");
			}
			outStr = sbuf.toString();
			// 要用来做导入用的sql目标文件：
			FileOutputStream fout = new FileOutputStream(
					BackupDBService.backuppath + "/"
							+ System.currentTimeMillis() + ".sql");
			OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
			writer.write(outStr);
			// 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
			writer.flush();
			// 别忘记关闭输入输出流
			in.close();
			xx.close();
			br.close();
			writer.close();
			fout.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}